﻿using System.Collections.Generic;

namespace ZeBobo5.LibraryHelper.Orm
{
    public class OrmDatabaseSchema
    {
        private static readonly List<IOrmDataLink> lstLinks = new List<IOrmDataLink>();

        public static void AddLink<A, B>(IOrmDataLink link)
            where A : IOrmDataElementBase
            where B : IOrmDataElementBase
        {
            if (!Exists(((OrmDataLink<A, B>) link).FieldA, ((OrmDataLink<A, B>) link).FieldB))
            {
                lstLinks.Add(link);
                lstLinks.Add(new OrmDataLink<B, A>(((OrmDataLink<A, B>) link).FieldB, ((OrmDataLink<A, B>) link).FieldA));
            }
        }

        public static void AddLinks<A, B>(params OrmDataLink<A, B>[] link)
            where A : IOrmDataElementBase
            where B : IOrmDataElementBase
        {
            foreach (OrmDataLink<A, B> dataLink in link)
            {
                AddLink<A, B>(dataLink);
            }
        }

        public static bool Exists<A, B>(OrmFieldBase<A> fieldA, OrmFieldBase<B> fieldB)
            where A : IOrmDataElementBase
            where B : IOrmDataElementBase
        {
            foreach (IOrmDataLink link in lstLinks)
            {
                if (link.TypeOfA == typeof (A) && link.TypeOfB == typeof (B))
                {
                    if (((OrmDataLink<A, B>) link).FieldA == fieldA && ((OrmDataLink<A, B>) link).FieldB == fieldB)
                    {
                        return true;
                    }
                }
            }
            return false;
        }

        public static List<OrmDataLink<A, B>> GetLinks<A, B>()
            where A : IOrmDataElementBase
            where B : IOrmDataElementBase
        {
            List<OrmDataLink<A, B>> links = new List<OrmDataLink<A, B>>();
            foreach (IOrmDataLink link in lstLinks)
            {
                if (link.TypeOfA == typeof (A) && link.TypeOfB == typeof (B))
                {
                    links.Add(link as OrmDataLink<A, B>);
                }
            }
            return links;
        }
    }
}